package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.dto.pyq.FeedMedia;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.PyqJobStatusEnum;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.MsgSplitUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.feign.uzaicms.CmsDtkTbGoodsDetailDto;
import com.uzai.console.dto.pyq.hdkgoods.PyqHdkGoodsJobBatchSendDao;
import com.uzai.console.dto.pyq.hdkgoods.PyqHdkGoodsJobSendDao;
import com.uzai.console.dto.pyq.pyqgoods.PyqJobBatchSendDao;
import com.uzai.console.dto.pyq.pyqgoods.PyqJobSendDao;
import com.uzai.console.entity.PyqDevicePlan;
import com.uzai.console.entity.PyqHdkGoods;
import com.uzai.console.entity.PyqJob;
import com.uzai.console.entity.PyqMaterial;
import com.uzai.console.mapper.PyqDevicePlanMapper;
import com.uzai.console.mapper.PyqHdkGoodsMapper;
import com.uzai.console.mapper.PyqJobMapper;
import com.uzai.console.mapper.PyqMaterialMapper;
import com.uzai.console.service.feign.UzaiCmsFeignService;
import com.uzai.console.service.pyq.*;
import com.uzai.console.vo.cms.tbgoods.DtkGoodsDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发送好单库商品朋友圈异步执行线程
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqHdkGoodsSyncServiceImpl implements PyqHdkGoodsSyncService {

    Logger logger = LoggerFactory.getLogger(PyqHdkGoodsSyncServiceImpl.class);

    @Autowired
    private PyqJobMapper pyqJobMapper;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private PyqMaterialService pyqMaterialService;
    @Autowired
    private PyqJobSyncService pyqJobSyncService;
    @Autowired
    private PyqHdkGoodsMapper pyqHdkGoodsMapper;
    @Autowired
    private PyqMaterialMapper pyqMaterialMapper;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;

    /**
     * 添加好单库商品群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    @Override
    @Async("taskExecutor")
    public void  batchAddJobSync(PyqHdkGoodsJobBatchSendDao pyqHdkGoodsJobBatchSendDao, List<Long> deviceUniqueIdList, PyqDevicePlan pyqDevicePlan){

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            return;
        }

        Integer now = DateUtil.getNowTime();
        //页面填写的发送时间
        Integer sendTime_page = now;
        //页面填写了发送时间
        if(pyqHdkGoodsJobBatchSendDao.getSendTime() != null ){
            sendTime_page = pyqHdkGoodsJobBatchSendDao.getSendTime();
        }
        Integer timeInterval = 0;
        //间隔时间,页面填写了间隔时间，单位为分钟
        if(pyqHdkGoodsJobBatchSendDao.getTimeInterval() != null){
            timeInterval = pyqHdkGoodsJobBatchSendDao.getTimeInterval() * 60;
        }
        List<Long> idList = pyqHdkGoodsJobBatchSendDao.getIdList();
        if(idList != null && idList.size() > 0){
            for (int i=0; i<idList.size(); i++){
                try{
                    Long id = idList.get(i);
                    PyqHdkGoods pyqHdkGoods = pyqHdkGoodsMapper.selectById(id);
                    if(pyqHdkGoods != null ){
                        //实际发送时间累加间隔时间(第一次不增加)
                        Integer sendTime_data = sendTime_page + timeInterval * i;
                        PyqJob pyqJob = new PyqJob();
                        pyqJob.setId(IdWorker.getId());
                        pyqJob.setMerId(pyqHdkGoodsJobBatchSendDao.getMerId());
                        pyqJob.setDeviceType(pyqDevicePlan.getDeviceType());
                        pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
                        pyqJob.setType(pyqHdkGoodsJobBatchSendDao.getType());
                        pyqJob.setSource(0); //手动发送
                        pyqJob.setPlatform(pyqHdkGoodsJobBatchSendDao.getPlatform());
                        pyqJob.setDevicePlanId(pyqHdkGoodsJobBatchSendDao.getDevicePlanId());
                        pyqJob.setItemId(pyqHdkGoods.getItemid());
                        pyqJob.setCouponId(pyqHdkGoods.getCouponid());
                        //图片
                        List<String> imgList = new ArrayList<>();
                        //添加商品图片
                        String itempic = Tools.getStr(pyqHdkGoods.getItempic());
                        if(StringUtils.isNotBlank(itempic)){
                            try {
                                List<String> itempicList = JSONArray.parseArray(itempic, String.class);
                                if(itempicList != null && itempicList.size() > 0){
                                    for (String item : itempicList){
                                        if(StringUtils.isNotBlank(item)){
                                            imgList.add(item);
                                        }
                                    }
                                }
                            }catch (Exception e){

                            }
                        }

                        if(StringUtils.isNotBlank(pyqHdkGoodsJobBatchSendDao.getCustomImg())){
                            imgList.add(Tools.getStr(pyqHdkGoodsJobBatchSendDao.getCustomImg()));
                        }

                        if(imgList.size() > 9){
                            imgList = imgList.subList(0, 9);
                        }

                        //新版朋友圈接口新增加字段
                        //封装附件类型
                        int attachType = 2; //默认图文
                        //封装附件对象
                        List<FeedMedia> feedMediaList = new ArrayList<>();
                        //封装视频号信息
                        String videoNumber = null;

                        if(imgList != null && imgList.size() > 0){
                            for (String item : imgList){
                                if(StringUtils.isNotBlank(item)){
                                    FeedMedia feedMedia = new FeedMedia();
                                    feedMedia.setMediaType(2);
                                    feedMedia.setUrl(item);
                                    feedMediaList.add(feedMedia);
                                }
                            }
                        }
                        pyqJob.setAttachType(2);//图文
                        pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
                        pyqJob.setVideoNumber(videoNumber);
                        pyqJob.setImgs(null);  //新版朋友圈接口，img不存放任何东西

                        pyqJob.setCouponVal(Tools.getDouble(pyqHdkGoods.getCouponmoney()));
                        pyqJob.setFinalPrice(Tools.getDouble(pyqHdkGoods.getItemendprice()));
                        pyqJob.setContentId(pyqHdkGoodsJobBatchSendDao.getContentId());
                        pyqJob.setCommentId(pyqHdkGoodsJobBatchSendDao.getCommentId());
                        pyqJob.setTotalCount(deviceUniqueIdList.size());
                        pyqJob.setCreateTime(now);
                        pyqJob.setUpdateTime(now);
                        pyqJob.setSendTime(sendTime_data);

                        //朋友圈内容替换变量
                        String content = Tools.getStr(pyqHdkGoodsJobBatchSendDao.getContent());

                        content = content.replace("[商品标题]",Tools.getStr(pyqHdkGoods.getItemtitle()))
                                .replace("[文案]",Tools.getStr(pyqHdkGoods.getCopyContent()))
                                .replace("[原价]",  String.valueOf(Tools.getDouble(pyqHdkGoods.getItemprice()).doubleValue()))
                                .replace("[券后价]", String.valueOf(Tools.getDouble(pyqHdkGoods.getItemendprice()).doubleValue()));

                        pyqJob.setContent(content);

                        //评论内容替换变量
                        List<String> commentList = new ArrayList<>();
                        //是否发送商品自带评论 1-开启
                        if(Tools.getInteger(pyqHdkGoodsJobBatchSendDao.getGoodsComment()).intValue() == 1){
                            //好单库自带的评论
                            String copyComment = Tools.getStr(pyqHdkGoods.getCopyComment());
                            String[] commentArr = copyComment.split("\\|");//"|"的转义字符为u007C
                            if(commentArr != null && commentArr.length > 0){
                                for (String comment : commentArr){
                                    if(StringUtils.isNotBlank(comment)){
                                        commentList.add(comment);
                                    }
                                }
                            }
                        }

                        //页面自定义评论
                        String commentContent = Tools.getStr(pyqHdkGoodsJobBatchSendDao.getCommentContent());

                        commentContent = commentContent.replace("[商品标题]",Tools.getStr(pyqHdkGoods.getItemtitle()))
                                .replace("[文案]",Tools.getStr(pyqHdkGoods.getCopyComment()))
                                .replace("[原价]",  String.valueOf(Tools.getDouble(pyqHdkGoods.getItemprice()).doubleValue()))
                                .replace("[券后价]", String.valueOf(Tools.getDouble(pyqHdkGoods.getItemendprice()).doubleValue()));

                        //追加页面自定义评论
                        List<String> commentContentList =  JSONArray.parseArray(commentContent, String.class);
                        if(commentContentList != null && commentContentList.size() > 0){
                            for(String demo : commentContentList){
                                if(StringUtils.isNotBlank(demo)){
                                    commentList.add(demo);
                                }
                            }
                        }

                        commentList.removeIf(s -> StringUtils.isBlank(s));
                        pyqJob.setCommentContent(JSONObject.toJSONString(commentList));

                        //后台添加发送明细
                        pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqHdkGoodsJobBatchSendDao.getDomain());
                    }
                }catch (Exception e){

                }
            }
        }

    }


    /**
     * 单个好单库商品添加群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    @Override
    @Async("taskExecutor")
    public void  addJobSync(PyqHdkGoodsJobSendDao pyqHdkGoodsJobSendDao, List<Long> deviceUniqueIdList, PyqDevicePlan pyqDevicePlan){

        logger.info("发送朋友圈的机器人数：num={}",deviceUniqueIdList.size());

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            return;
        }

        Long id = pyqHdkGoodsJobSendDao.getId();
        PyqHdkGoods pyqHdkGoods = pyqHdkGoodsMapper.selectById(id);

        if(pyqHdkGoods == null){
            return;
        }

        Integer now = DateUtil.getNowTime();
        //发送时间
        Integer sendTime = now;
        //页面填写了发送时间
        if(pyqHdkGoodsJobSendDao.getSendTime() != null ){
            sendTime = pyqHdkGoodsJobSendDao.getSendTime();
        }

        PyqJob pyqJob = new PyqJob();
        pyqJob.setId(IdWorker.getId());
        pyqJob.setMerId(pyqHdkGoodsJobSendDao.getMerId());
        pyqJob.setDeviceType(pyqDevicePlan.getDeviceType());
        pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
        pyqJob.setType(pyqHdkGoodsJobSendDao.getType());
        pyqJob.setSource(0); //手动发送
        pyqJob.setPlatform(pyqHdkGoodsJobSendDao.getPlatform());
        pyqJob.setDevicePlanId(pyqHdkGoodsJobSendDao.getDevicePlanId());
        pyqJob.setItemId(pyqHdkGoodsJobSendDao.getItemid());
        pyqJob.setCouponId(pyqHdkGoodsJobSendDao.getActivityid());
        //图片
        List<String> imgList = pyqHdkGoodsJobSendDao.getImgList();
        if(imgList != null && imgList.size() > 9){
            imgList = imgList.subList(0, 9);
        }

        //新版朋友圈接口新增加字段
        //封装附件类型
        int attachType = 2; //默认图文
        //封装附件对象
        List<FeedMedia> feedMediaList = new ArrayList<>();
        //封装视频号信息
        String videoNumber = null;

        if(imgList != null && imgList.size() > 0){
            for (String item : imgList){
                if(StringUtils.isNotBlank(item)){
                    FeedMedia feedMedia = new FeedMedia();
                    feedMedia.setMediaType(2);
                    feedMedia.setUrl(item);
                    feedMediaList.add(feedMedia);
                }
            }
        }
        pyqJob.setAttachType(2);//图文
        pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
        pyqJob.setVideoNumber(videoNumber);
        pyqJob.setImgs(null);  //新版朋友圈接口，img不存放任何东西

        pyqJob.setCouponVal(pyqHdkGoodsJobSendDao.getCouponmoney());
        pyqJob.setFinalPrice(pyqHdkGoodsJobSendDao.getItemendprice());
        pyqJob.setContentId(pyqHdkGoodsJobSendDao.getContentId());
        pyqJob.setCommentId(pyqHdkGoodsJobSendDao.getCommentId());
        pyqJob.setTotalCount(deviceUniqueIdList.size());
        pyqJob.setCreateTime(now);
        pyqJob.setUpdateTime(now);
        pyqJob.setSendTime(sendTime);

        //朋友圈内容替换变量
        String content = Tools.getStr(pyqHdkGoodsJobSendDao.getContent());
        //券后价
        Double itemendprice = Tools.getDouble(pyqHdkGoodsJobSendDao.getItemendprice());
        //优惠券金额
        Double couponmoney = Tools.getDouble(pyqHdkGoodsJobSendDao.getCouponmoney());
        //原价 itemprice
        Double itemprice = Tools.getDouble(pyqHdkGoodsJobSendDao.getItemprice());
        content = content.replace("[商品标题]",Tools.getStr(pyqHdkGoodsJobSendDao.getItemtitle()))
                .replace("[文案]",Tools.getStr(pyqHdkGoods.getCopyContent()))
                .replace("[原价]",  String.valueOf(itemprice.doubleValue()))
                .replace("[券后价]", String.valueOf(itemendprice.doubleValue()));
        pyqJob.setContent(content);
        //评论内容替换变量
        String commentContent = Tools.getStr(pyqHdkGoodsJobSendDao.getCommentContent());
        commentContent = commentContent.replace("[商品标题]",Tools.getStr(pyqHdkGoodsJobSendDao.getItemtitle()))
                .replace("[文案]",Tools.getStr(pyqHdkGoods.getCopyContent()))
                .replace("[原价]",  String.valueOf(itemprice.doubleValue()))
                .replace("[券后价]", String.valueOf(itemendprice.doubleValue()));

        //去空评论
        List<String> commentContentList = JSONObject.parseArray(commentContent, String.class);
        if(commentContentList != null && commentContentList.size() > 0) {
            commentContentList.removeIf(s -> StringUtils.isBlank(s));
            commentContent = JSONObject.toJSONString(commentContentList);
        }
        pyqJob.setCommentContent(commentContent);

        //后台添加发送明细
        pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqHdkGoodsJobSendDao.getDomain());

        //保存为素材
        if(Tools.getInteger(pyqHdkGoodsJobSendDao.getSaveMaterialFlag()).intValue() == 1){ //保存素材
            PyqMaterial pyqMaterial = new PyqMaterial();
            pyqMaterial.setId(IdWorker.getId());
            pyqMaterial.setMerId(pyqJob.getMerId());
            pyqMaterial.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            pyqMaterial.setType(pyqJob.getType());
            pyqMaterial.setPlatform(pyqJob.getPlatform());
            pyqMaterial.setDevicePlanId(pyqJob.getDevicePlanId());
            pyqMaterial.setItemId(pyqJob.getItemId());
            pyqMaterial.setCouponId(pyqJob.getCouponId());
            pyqMaterial.setCouponVal(pyqJob.getCouponVal());
            pyqMaterial.setFinalPrice(pyqJob.getFinalPrice());
            pyqMaterial.setContentId(pyqJob.getContentId());
            pyqMaterial.setContent(pyqJob.getContent());
            pyqMaterial.setImgs(pyqJob.getImgs());
            pyqMaterial.setCommentId(pyqJob.getCommentId());
            pyqMaterial.setCommentContent(pyqJob.getCommentContent());

            //新版朋友圈接口新增加字段
            pyqMaterial.setAttachType(pyqJob.getAttachType());
            pyqMaterial.setVideoNumber(pyqJob.getVideoNumber());
            pyqMaterial.setFeedMedia(pyqJob.getFeedMedia());
            pyqMaterial.setImgs(null);  //新版朋友圈接口，img不存放任何东西

            pyqMaterial.setCreateTime(now);
            pyqMaterial.setUpdateTime(now);
            pyqMaterialMapper.insert(pyqMaterial);
        }
    }

}
